package com.bx.demo;

import com.alibaba.nacos.api.annotation.NacosInjected;
import com.alibaba.nacos.api.config.annotation.NacosValue;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.api.naming.NamingService;
import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import com.alibaba.nacos.spring.context.annotation.discovery.EnableNacosDiscovery;
import com.bx.demo.web.api.Api;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.web.client.RestTemplate;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Arrays;

/**
 * @author J
 */
@SpringBootApplication
@NacosPropertySource(dataId = "Master", autoRefreshed = true)
@EnableNacosDiscovery
public class DemoApplication implements CommandLineRunner {

    private static final Logger log = LoggerFactory.getLogger(DemoApplication.class);

    @NacosInjected
    private NamingService namingService;
    @NacosValue("${spring.application.name}")
    private String applicationName;
    @NacosValue("${server.port}")
    private Integer serverPort;

    public static void main(String[] args) throws UnknownHostException {
        ConfigurableApplicationContext run = SpringApplication.run(DemoApplication.class, args);
        ConfigurableEnvironment env = run.getEnvironment();
        String ip = InetAddress.getLocalHost().getHostAddress();
        String port = env.getProperty("server.port");
        log.info("\n----------------------------------------------------------\n\t" +
                "Application  is running! Access URLs:\n\t" +
                "Local访问网址: \t\thttp://localhost:" + port + "\n\t" +
                "External访问网址: \thttp://" + ip + ":" + port + "\n\t" +
                "----------------------------------------------------------");

//        String[] beanNames = run.getBeanDefinitionNames();
//        Arrays.sort(beanNames);
//        for (String s : beanNames) {
//            System.out.println(s);
//        }
    }

    /**
     *     容器启动后最后一步回调类似开机启动
     *     nacos 服务注册
     *
     */
	@Override
	public void run(String... args) throws NacosException {
        namingService.registerInstance(applicationName,"127.0.0.1", serverPort);
	}

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }
}
